package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.RelativeDateFormat;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserVo;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.VisitorApi;
import com.tanhua.server.interceptors.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class MovementService {


    @DubboReference
    private MovementApi movementApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    public ResponseEntity saveMovements(Movement movement, MultipartFile[] imageContent) throws Exception {

//        1、先保存图片 上传到阿里云 返回url
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            medias.add(url);
        }

        movement.setUserId(UserHolder.getUserId());
        movement.setMedias(medias);
        String movementId = movementApi.saveMovements(movement);
//        向mq中发送一个动态id
        rabbitTemplate.convertAndSend("movement.exchange","movement.save",movementId);
        return ResponseEntity.ok(null);


    }

    public ResponseEntity queryFriendMovements(Integer page, Integer pagesize) {
//        1、查询mongo  返回 PageResult  pageResult

        PageResult  pageResult = movementApi.queryFriendMovements(UserHolder.getUserId(),page,pagesize);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : movementList) {
            Long userId = movement.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);

            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);

            list.add(movementsVo);
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryRecommendMovements(Integer page, Integer pagesize) {


        PageResult  pageResult = movementApi.queryRecommendMovements(UserHolder.getUserId(),page,pagesize);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : movementList) {
            Long userId = movement.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);

            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);

            list.add(movementsVo);
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);
    }

    public MovementsVo movementAndUserInfoToMovementVo(Movement movement, UserInfo userInfo) {
        MovementsVo movementsVo = new MovementsVo();

        BeanUtils.copyProperties(userInfo, movementsVo);
//            仍然需要手动赋值的是 id  userId  tags
        movementsVo.setId(movement.getId().toString());//动态id
        movementsVo.setUserId(userInfo.getId());
        if (StringUtils.isNotBlank(userInfo.getTags())) {
            movementsVo.setTags(userInfo.getTags().split(","));
        }

        BeanUtils.copyProperties(movement, movementsVo);
//            仍然需要手动赋值的是 imageContect  distance  createDate

        movementsVo.setImageContent(movement.getMedias().toArray(new String[]{}));
        movementsVo.setDistance("500米");// TODO 完成搜附近的人再做
        movementsVo.setCreateDate(RelativeDateFormat.format(new Date(movement.getCreated())));

//        comment  当前登录人是否对这个圈子点赞
//        select * from comment where userId=??? and publishId=??? and commentType=1
        if(redisTemplate.hasKey("movement_like_" + UserHolder.getUserId() + "_" + movement.getId().toString())){
            movementsVo.setHasLiked(1);// 当前登录人是否对这个圈子点赞
        }else{
            movementsVo.setHasLiked(0);
        }
        if(redisTemplate.hasKey("movement_love_" + UserHolder.getUserId() + "_" + movement.getId().toString())){
            movementsVo.setHasLoved(1);// 当前登录人是否对这个圈子喜欢
        }else{
            movementsVo.setHasLoved(0);
        }

//            movementsVo.setHasLoved(); 当前登录人是否对这个圈子喜欢
        return movementsVo;
    }

    public ResponseEntity queryMyselfMovements(Integer page, Integer pagesize, Long userId) {

        if(userId==null){
            userId = UserHolder.getUserId();
        }
        PageResult  pageResult = movementApi.queryMyselfMovements(userId,page,pagesize);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : movementList) {

            if(movement.getState()!=1){
                continue;
            }

            UserInfo userInfo = userInfoApi.findById(movement.getUserId());

            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);

            list.add(movementsVo);
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);
    }


    @DubboReference
    private CommentApi commentApi;
    @Autowired
    private StringRedisTemplate redisTemplate;

//    圈子点赞方法
    public ResponseEntity like(String movementId) {
//        保存comment  圈子点赞数+1  返回点赞数
        Comment comment = new Comment();

        comment.setPublishId(new ObjectId(movementId)); // 圈子id
        comment.setCommentType(1); //评论类型，1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
//        comment.setContent(); //评论的内容
        comment.setUserId(UserHolder.getUserId());  //
//        comment.setLikeCount(); //这个评论收到的点赞数据

//        comment.setId();  //主键 ObjectId
//        comment.setCreated(); // new Date()
//        comment.setPublishUserId(); // 对谁发布的圈子点赞

        Integer count =  commentApi.save(comment);

//        向redis中放一个标记数据：当前登录人对这个圈子已点赞
        redisTemplate.boundValueOps("movement_like_"+UserHolder.getUserId()+"_"+movementId).set("");

        return ResponseEntity.ok(count);
    }

    public ResponseEntity dislike(String movementId) {
//       delete comment  圈子点赞数-1  返回点赞数
//        当前登录人对XX圈子的点赞
//        delete from comment where userId=?? and pulishId=?? and commentType=1
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(1);
        comment.setUserId(UserHolder.getUserId());
        Integer count =  commentApi.delete(comment);

        redisTemplate.delete("movement_like_"+UserHolder.getUserId()+"_"+movementId);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity love(String movementId) {
        //        保存comment  圈子喜欢数+1  返回喜欢数
        Comment comment = new Comment();

        comment.setPublishId(new ObjectId(movementId)); // 圈子id
        comment.setCommentType(3); //评论类型，1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
//        comment.setContent(); //评论的内容
        comment.setUserId(UserHolder.getUserId());  //
//        comment.setLikeCount(); //这个评论收到的喜欢数
        Integer count =  commentApi.save(comment);

//        向redis中放一个标记数据：当前登录人对这个圈子已喜欢
        redisTemplate.boundValueOps("movement_love_"+UserHolder.getUserId()+"_"+movementId).set("");

        return ResponseEntity.ok(count);
    }

    public ResponseEntity unlove(String movementId) {
        //       delete comment  圈子喜欢数-1  返回喜欢数
//        当前登录人对XX圈子的喜欢
//        delete from comment where userId=?? and pulishId=?? and commentType=3
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(3);
        comment.setUserId(UserHolder.getUserId());
        Integer count =  commentApi.delete(comment);

        redisTemplate.delete("movement_love_"+UserHolder.getUserId()+"_"+movementId);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity queryMovementsById(String movementId) {

        Movement movement = movementApi.queryMovementsById(movementId);
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());

        MovementsVo movementsVo =  movementAndUserInfoToMovementVo(movement,userInfo);

        return ResponseEntity.ok(movementsVo);


    }

    @DubboReference
    private VisitorApi visitorApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;

    public ResponseEntity queryVisitors(int num) {
//        查询mongo
       List<Visitors> visitorsList  = visitorApi.queryVisitors(UserHolder.getUserId(),num);

       List<RecommendUserVo> list=  new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            UserInfo userInfo = userInfoApi.findById(visitors.getVisitorUserId());
            BeanUtils.copyProperties(userInfo,recommendUserVo);

            if(userInfo.getTags()!=null){
              recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            Long score = recommendUserApi.queryScore(UserHolder.getUserId(), visitors.getVisitorUserId());
            recommendUserVo.setFateValue(score);
            list.add(recommendUserVo);
        }

       return ResponseEntity.ok(list);

    }
}
